package com.o2opuzi.ms.web.admin.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.o2opuzi.lib.util.ResultMap;
import com.o2opuzi.lib.web.WebHelper;
import com.o2opuzi.ms.model.user.User;
import com.o2opuzi.ms.service.sys.SysRoleService;
import com.o2opuzi.ms.service.user.UserLoginService;
import com.o2opuzi.ms.service.user.exception.UserLoginException;

/**
 * 管理员登录
 * @author Y.hj
 * @date 2016年5月31日
 */
@RestController
public class AdminLoginController {
	
	@Autowired
	private UserLoginService userLoginService;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	
	/**
	 * 管理员登录
	 * @auther Y.hj
	 * @param account 登录账号
	 * @param password 登录密码
	 * @param redirect_url 返回的url 
	 * @param helper
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public Object doLogin(String account,String password,String redirect_url,WebHelper helper){
		ResultMap ret = new ResultMap();
		try {
			//获取登录的用户
			User user = userLoginService.login(
					account, 
					password,
					helper.getIpAddress(),
					helper.getClientType()
			);
			//验证权限
			//是否是管理员
			if(!user.getIsadmin().equals(1)){
				ret.put("code", 0);
				ret.put("msg", "没有权限");
			}
			
			
			
			
			ret.put("code", 1);
			ret.put("msg", "登陆成功");
		} catch (UserLoginException e) {
			ret.put("code", 0);
			ret.put("msg", e.getMessage());
		}
		
		return ret;
	}
	
	/***
	 * 登录验证
	 * @auther Y.hj
	 * @param helper
	 * @return
	 */
	@RequestMapping(value="/login/valid",method=RequestMethod.GET)
	public Object loginCheck(WebHelper helper){
		String loginToken = helper.getRequest().getHeader("x-login-token");
		if(StringUtils.isEmpty(loginToken)){
			loginToken = helper.getParam("x-login-token");
		}
		if(StringUtils.isEmpty(loginToken)){
			loginToken = helper.getCookieValue("x-login-token");
		}
		
		return null;
	}
}
